package com.ld.zxw.Documents;

import java.util.List;

import org.apache.lucene.document.BinaryPoint;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.DoublePoint;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FloatPoint;
import org.apache.lucene.document.IntPoint;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.util.BytesRef;

import com.ld.zxw.util.BoostDto;
/**
 * 字段添加
 * @author Administrator
 *
 */
public class Documents {


	private Document document;

	private List<BoostDto> boosts = null;


	public Documents(List<BoostDto> boosts) {
		document = new Document();
		this.boosts = boosts;
	}

	public void put(String key,String val, String type, float boost){
		addField(key, val == null ? "" : val, type, boost);
	}

	public Document getDocument(){
		return this.document;
	}



	/**
	 * 
	 * @param name key
	 * @param value val
	 * @param boost 权重
	 * @param type  字段类型
	 */
	@SuppressWarnings("deprecation")
	public void addField(String name, String value,String type,float boost){
		switch (type) {
		case "int":
			int point_i = Integer.parseInt(value);
			document.add(new IntPoint(name, point_i));
			document.add(new StoredField(name, point_i));
			document.add(new NumericDocValuesField(name, point_i));
			break;
		case "float":
			float point_f = Float.valueOf(value);
			document.add(new FloatPoint(name, point_f));
			document.add(new StoredField(name, point_f));
			break;
		case "binary":
			byte[] point_b = value.getBytes();
			document.add(new BinaryPoint(name, point_b));
			document.add(new StoredField(name, point_b));
			break;
		case "double":
			double point_d = Double.valueOf(value);
			document.add(new DoublePoint(name, point_d));
			document.add(new StoredField(name, point_d));
			break;
		case "string":
			document.add(new StringField(name, value, Field.Store.YES));
			document.add(new SortedDocValuesField(name, new BytesRef(value)));
			break;
		case "text":
			TextField textField = new TextField(name, value, Field.Store.YES);
			//动态权重
			if(boosts != null) {
				int size = boosts.size();
				for (int k = 0; k < size; k++) {
					BoostDto boostDto = boosts.get(k);
					if(boostDto.getName().equals(value)) {
						boost = boost + boostDto.getBoost();
						break;
					}
				}
			}
			textField.setBoost(boost);
			document.add(textField);
			break;
		}
	}
}
